package com.bluse.aop;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;


@Aspect
@Component
public class LoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    private Environment env;

    public LoggingAspect(Environment env) {
        this.env = env;
    }


    /**
     * Define the pointcut of  call Controller  layer
     */
    @Pointcut(value = "within(com.bluse.controller.*)")
    private void controllerPointcut() {

    }


    /**
     * Call the controller layer  method to output logging on  console window
     */
    @AfterReturning(pointcut = "controllerPointcut()")
    private void callControllerLayerThrowing(JoinPoint joinPoint) {
        if (logger.isWarnEnabled()) {
            logger.info("Enter {}.{}() with arguments[s]={}", joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
        }
        try {
            Object result = joinPoint.getTarget();
            if (logger.isWarnEnabled()) {
                logger.info("Exit:{}.{}() with result={}", joinPoint.getSignature().getDeclaringTypeName(),
                        joinPoint.getSignature().getName(), result);
            }
        } catch (IllegalArgumentException e) {
            logger.error("Illegal Argument:{} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
                    joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        }


    }


}
